// 获取启用状态
async function isEnabled() {
  const data = await browser.storage.local.get('enabled');
  return data.enabled !== false; // 默认为true
}

// 从存储中获取URL映射
async function getUrlMappings() {
  const data = await browser.storage.local.get('urlMappings');
  return data.urlMappings || {};
}

// 请求拦截逻辑
browser.webRequest.onBeforeRequest.addListener(
  async (details) => {
    // 检查是否启用
    if (!(await isEnabled())) {
      return {};
    }
    
    const mappings = await getUrlMappings();
    
    for (const [original, target] of Object.entries(mappings)) {
      try {
        const originalRegex = new RegExp(original);
        if (originalRegex.test(details.url)) {
          const redirectUrl = details.url.replace(originalRegex, target);
          
          console.log(`Redirecting: ${details.url} → ${redirectUrl}`);
          return { redirectUrl };
        }
      } catch (e) {
        console.error(`Error processing regex ${original}:`, e);
      }
    }
    
    return {};
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);

// 初始化存储的启用状态
browser.storage.local.get('enabled').then(data => {
  if (data.enabled === undefined) {
    // 设置默认值为true
    browser.storage.local.set({ enabled: true });
  }
});